<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['technology:drawing-work-task:save']"
        v-show="!formType && [10, 20, 30, 50].includes(formData.dictStatus)"
        >保 存</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <p class="baseTitle">基本信息</p>
      <el-form ref="formRef" :model="formData" :inline="true" label-width="100px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="formData.orderNumber" placeholder="请输入订单号" disabled />
        </el-form-item>
        <el-form-item label="订单类型" prop="dictOrderType">
          <el-select v-model="formData.dictOrderType" placeholder="请选择订单类型" disabled>
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.MARKET_ORDER_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="formData.customerCode" placeholder="请输入客户代码" disabled />
        </el-form-item>
        <el-form-item label="任务类型" prop="dictTaskType">
          <el-select v-model="formData.dictTaskType" placeholder="请选择任务类型" disabled>
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.TASK_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号" prop="productNumber">
          <el-input v-model="formData.productNumber" placeholder="请输入产品编号" disabled />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input v-model="formData.productStandard" placeholder="请输入产品规格" disabled />
        </el-form-item>
        <el-form-item label="交货日期" prop="deliveryTime">
          <el-date-picker
            v-model="formData.deliveryTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择交货日期"
            disabled
          />
        </el-form-item>
        <el-form-item label="下单日期" prop="placeOrderDate">
          <el-date-picker
            v-model="formData.placeOrderDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择下单日期"
            disabled
          />
        </el-form-item>
        <el-form-item label="订单数量" prop="orderQuantity">
          <el-input v-model="formData.orderQuantity" placeholder="请输入订单数量" disabled />
        </el-form-item>
      </el-form>
      <p class="baseTitle">派工详情</p>
      <el-table ref="tableRef" :data="formData.orderTasks" style="width: 100%" border class="table">
        <el-table-column type="index" width="80" label="序号" align="center" />
        <el-table-column
          :property="item.val"
          :label="item.label"
          :min-width="item.width"
          :key="item.val"
          v-for="item in tableTitle"
          align="left"
          header-align="left"
        >
          <template #default="scope">
            <template v-if="['proportion', 'explaind'].includes(item.val)">
              <el-input
                v-nextInput="item.val"
                :name="item.val"
                v-model="scope.row[item.val]"
                :disabled="formType || (item.val == 'proportion' && scope.row.dictIsDrawing == 20)"
                :type="item.val == 'proportion' ? 'number' : 'text'"
              />
            </template>
            <template v-else-if="['dictDrawingType', 'dictIsDrawing'].includes(item.val)">
              <el-select
                v-model="scope.row[item.val]"
                :disabled="
                  formType ||
                  item.val == 'dictDrawingType' ||
                  (item.val == 'dictIsDrawing' && formData.dictStatus != 10)
                "
                @change="(e) => changeDictIsDrawing(e, scope.$index)"
              >
                <el-option
                  v-for="dict in getIntDictOptions(item.dict)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
            <template v-else-if="['jobNumber'].includes(item.val)">
              <el-select
                v-model="scope.row[item.val]"
                filterable
                remote
                reserve-keyword
                :remote-method="
                  (e) => {
                    getSelectDesignersList(e, scope.$index)
                  }
                "
                :loading="designersLoading"
                class="!w-120px"
                :disabled="formType"
              >
                <el-option
                  v-for="dict in scope.row.designersList"
                  :key="dict.jobNumber"
                  :label="dict.designerPersonName"
                  :value="dict.jobNumber"
                />
              </el-select>
            </template>
            <template v-else>
              <el-date-picker
                v-model="scope.row[item.val]"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="`选择${item.label}`"
                :disabled="formType"
              />
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as DrawingWorkTaskApi from '@/api/technology/drawingWorkTask'
  import * as componentApi from '@/api/componentApi'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formData = ref({
    id: undefined,
    orderNumber: undefined,
    productNumber: undefined,
    dictTaskType: undefined,
    deliveryTime: undefined,
    placeOrderDate: undefined,
    dictOrderType: undefined,
    customerCode: undefined,
    productStandard: undefined,
    orderQuantity: undefined,
    orderTasks: undefined
  })
  /**表头 */
  const tableTitle = ref([
    {
      label: '占比(%)',
      val: 'proportion',
      width: 100
    },
    {
      label: '出图类型',
      val: 'dictDrawingType',
      dict: 'drawing_type',
      width: 150
    },
    {
      label: '说明',
      val: 'explaind',
      width: 200
    },
    {
      label: '设计员',
      val: 'jobNumber',
      width: 200
    },
    {
      label: '产品制图开始日期',
      val: 'planStartDate',
      width: 200
    },
    {
      label: '产品制图结束日期',
      val: 'planEndDate',
      width: 200
    },
    {
      label: '是否出图',
      val: 'dictIsDrawing',
      dict: 'is_drawing',
      width: 100
    }
  ])

  /**修改是否出图 */
  const changeDictIsDrawing = (res: number, index: number) => {
    //如果不用出图
    if (res == 20) {
      formData.value.orderTasks[index].proportion = 0
    }
  }
  /** 提交表单 */
  const submitForm = async () => {
    // 提交请求

    const data = formData.value as unknown as DrawingWorkTaskApi.DrawingWorkTaskVO

    //是否需要校验订单类型为维修
    let isMaintenance = undefined
    //如果都是不出图，则校验是否为维修
    if (data.orderTasks[0].dictIsDrawing == 20 && data.orderTasks[1].dictIsDrawing == 20) {
      isMaintenance = true
    } else {
      isMaintenance = false
    }
    //如果不需要校验订单类型是否为维修，进入正常校验
    if (!isMaintenance) {
      //校验占比之和
      let num = 0
      //校验规则
      const fillRule = ['', undefined, null]
      let isPass = false
      data.orderTasks.map((item) => {
        //如果需要出图，则相加
        if (item.dictIsDrawing == 10) {
          if (item.proportion <= 0) {
            message.error(`产品占比不能小于等于0`)
            isPass = true
          }
          num += parseFloat(item.proportion)
          if (
            fillRule.includes(item.jobNumber) ||
            fillRule.includes(item.planStartDate) ||
            fillRule.includes(item.planEndDate)
          ) {
            message.error(`设计人员/产品制图开始日期/产品制图结束日期不能为空`)
            isPass = true
          }
        }
        if (item.designersList.length) {
          item.designerPersonName = item.designersList.filter(
            (data) => data.jobNumber == item.jobNumber
          )[0].designerPersonName
        }
      })
      if (isPass) {
        return
      }
      if (num != 100) {
        message.error('占比之合必须为100!')
        return
      }
    } else {
      //如果需要校验订单类型是否为维修
      if (data.dictOrderType != 20) {
        message.error('订单类型不是维修，请选择一种出图类型进行出图')
        return
      }
    }
    //校验产品制图结束日期不能早于产品制图开始日期
    for (let i = 0; i < data.orderTasks.length; i++) {
      const event = data.orderTasks[i]
      if (event.planEndDate < event.planStartDate) {
        message.error('产品制图结束日期不能早于产品制图开始日期')
        return
      }
    }
    formLoading.value = true
    try {
      await DrawingWorkTaskApi.updateDrawingWorkTask(data)
      message.success(t('common.updateSuccess'))
      goBack()
    } finally {
      formLoading.value = false
    }
  }

  /**设计员搜索 */
  const designersLoading = ref(false)
  const getSelectDesignersList = async (keyword: string, index: number) => {
    designersLoading.value = true
    let data = await componentApi.getDesignersList(keyword)
    formData.value.orderTasks[index].designersList = data
    designersLoading.value = false
  }

  /**返回 */
  const tagsViewStore = useTagsViewStore()
  const route = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(route.currentRoute.value)
    //跳转列表页
    route.push({
      path: '/technology/technology/drawingProduction/drawingWorkTask'
    })
  }

  /** 初始化 */
  const { query } = useRoute() // 路由的查询
  const formType = ref(false) //是否可编辑
  const contentHeight = ref(0)
  onMounted(async () => {
    formLoading.value = true
    //edit:编辑 view:查看
    formType.value = query.type == 'edit' ? false : true
    if (query.id) {
      formData.value = await DrawingWorkTaskApi.getDrawingWorkTask(query.id)
      //如果没有数据则固定两条制图类型数据
      console.log(!formData.value.orderTasks.length)
      if (!formData.value.orderTasks.length) {
        formData.value.orderTasks = [
          {
            proportion: 0,
            dictDrawingType: 10,
            explaind: null,
            jobNumber: null,
            planStartDate: null,
            planEndDate: null,
            dictIsDrawing: 10,
            designersList: []
          },
          {
            proportion: 0,
            dictDrawingType: 20,
            explaind: null,
            jobNumber: null,
            planStartDate: null,
            planEndDate: null,
            dictIsDrawing: 10,
            designersList: []
          }
        ]
      } else {
        formData.value.orderTasks[0].designersList = []
        formData.value.orderTasks[1].designersList = []
        getSelectDesignersList(formData.value.orderTasks[0].designerPersonName, 0)
        getSelectDesignersList(formData.value.orderTasks[1].designerPersonName, 1)
      }
    }
    contentHeight.value = document.body.clientHeight - 127
    console.log(formData.value)
    formLoading.value = false
  })
</script>
<style lang="scss" scoped>
  .contentView {
    padding: 10px;
    background: #fff;
  }

  .routeHeader {
    width: 100%;
    border-bottom: 1px solid #969696;
    display: flex;
    align-items: center;
    padding: 10px 0;
  }

  .baseTitle {
    font-weight: bold;
    padding: 20px 0;
  }

  .table {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;

      .el-input__inner {
        cursor: default !important;
        text-align: left;
      }
    }
  }
</style>
